package com.zyf.project.kvdb.protocol.codec;

import com.zyf.project.binaryproto.common.BinaryProtocol;
import com.zyf.project.binaryproto.common.DataContractRegistry;
import com.zyf.project.kvdb.protocol.proto.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jetbrains.annotations.NotNull;

/**
 * <h1>KVDB 编码器</h1>
 * <p>继承了 Netty 的 {@link MessageToByteEncoder} 接口，泛型为 {@link Message}</p>
 *
 * @author Zhou Yifan
 */
public class KVDBEncoder extends MessageToByteEncoder<Message> {

    static {
        DataContractRegistry.register(Message.class);
        DataContractRegistry.register(Command.class);
        DataContractRegistry.register(MessageContent.class);
        DataContractRegistry.register(Response.class);
        DataContractRegistry.register(DatabaseClusterInfo.class);
        DataContractRegistry.register(ClusterItem.class);
        DataContractRegistry.register(ClusterInfo.class);
        DataContractRegistry.register(DatabaseBaseInfo.class);
        DataContractRegistry.register(DatabaseBaseInfos.class);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, @NotNull ByteBuf out) {
        out.writeBytes(BinaryProtocol.encode(msg, Message.class));
    }

}
